import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sports_new/controller/service/resource_service.dart';
import 'package:sports_new/entity/other/resource_entity.dart';
import 'package:sports_new/server/api/other_api.dart';
import 'package:sports_new/utils/utils.dart';
import '../../base/base_controller.dart';
import '../../entity/home/subs_list_entity.dart';
import '../../server/api/expert_api.dart';
import '../../utils/user.dart';

class SubsLogic extends BaseController with GetSingleTickerProviderStateMixin{
  List<String> tabs = ["订阅","关注","连红","回报","命中"];
  int? roomId = Get.parameters['roomId'].toInt();
  late TabController tabController = TabController(length: tabs.length, vsync: this,initialIndex: _tabIndex);
  late List<List<SubsListEntity>?> items = List.generate(tabs.length, (index) => null);
  int _tabIndex = 2;
  late List<int> loadIndex = List.generate(tabs.length, (index) => 1);
  List<ResourceEntity>? lbt;
  int pageSize = 15;

  int get tabIndex => _tabIndex;

  set tabIndex(int value) {
    _tabIndex = value;
    update();
  }

  @override
  void onInit() {
    tabController.addListener(() {
      tabIndex = tabController.index;
      if(items[tabIndex] == null) getData();
    });
    super.onInit();
  }

  @override
  void onReady() {
    getData();
    getResource();
    super.onReady();
  }

  Future getData() async{
    loadIndex[tabIndex] = 1;
    if((tabIndex == 0 || tabIndex == 1) && !User.isLogin) {
      items[tabIndex] = [];
      update();
      return;
    }
    items[tabIndex] = await ExpertApi.getSubsList(tabIndex+1,loadIndex[tabIndex],pageSize);
    update();
  }

  Future getResource() async {
    final result = Get.find<ResourceService>().lbt;
    lbt = result.where((element) => element.button == "subs").toList();
    update();
  }

  @override
  Future getRefresh() async{
    getData();
    getResource();
  }

  @override
  void loadMore() async{
    loadIndex[tabIndex] += 1;
    items[tabIndex] = await ExpertApi.getSubsList(tabIndex+1,loadIndex[tabIndex],pageSize);
    refreshController.finishLoad(
        (items[tabIndex]?.length ?? 0) < pageSize * loadIndex[tabIndex]
            ? IndicatorResult.noMore : IndicatorResult.success
    );
    update();
    super.loadMore();
  }
}